import { useContext, useRef } from "react";
import * as actions from "../../useReducerStore/action/count";
import { AppContext } from ".";

export default function useCount() {
  const ctx: any = useContext(AppContext);
  const { sum } = ctx.appState.counts || 0;
  let numberNode: any = useRef<HTMLDivElement | null>(null);
  const increment = () => {
    const { value } = numberNode;
    ctx.dispatch(actions.increment(value * 1));
  };
  const decrement = () => {
    const { value } = numberNode;
    ctx.dispatch(actions.decrement(value * 1));
  };
  const incrementIfOdd = () => {
    const { value } = numberNode;
    if (sum % 2 !== 0) {
      ctx.dispatch(actions.increment(value * 1));
    }
  };
  const incrementAsync = () => {
    const { value } = numberNode;
    setTimeout(() => {
      ctx.dispatch(actions.increment(value * 1));
    }, 500);
  };
  return (
    <>
      <h1>求和组件</h1>
      <h2>當前求和{sum}</h2>
      <select
        ref={(c) => {
          numberNode = c;
        }}
      >
        <option value="1">1</option>
        <option value="2">2</option>
        <option value="3">3</option>
      </select>
      <button onClick={increment}>+</button>
      <button onClick={decrement}>-</button>
      <button onClick={incrementIfOdd}>奇數+</button>
      <button onClick={incrementAsync}>異步+</button>
    </>
  );
}
